/**
 * 退款计算工具类
 * 根据用户退改规则计算退款金额
 */

const { query } = require('../config/db');
const pricingEngine = require('./pricingEngine');

class RefundCalculator {
  
  /**
   * 计算取消订单的退款金额
   * @param {Object} order - 订单信息
   * @param {Date} cancelTime - 取消时间
   * @returns {Promise<Object>} 退款计算结果
   */
  async calculateCancelRefund(order, cancelTime = new Date()) {
    try {
      const plannedStartTime = new Date(order.planned_start_time);
      const finalAmount = parseFloat(order.final_amount);
      
      // 判断是否在预计入场时间前取消
      const isBeforeEntry = cancelTime < plannedStartTime;
      
      if (isBeforeEntry) {
        // 预计入场时间前可自助取消，支付的费用全额原路退回
        return {
          success: true,
          canCancel: true,
          refundAmount: finalAmount,
          serviceFee: 0,
          refundReason: '预计入场时间前取消，全额退款',
          refundType: 'full_refund'
        };
      } else {
        // 超过预计入场时间，取消需支付10%的车位预留服务费
        const serviceFee = Math.round(finalAmount * 0.1 * 100) / 100; // 保留两位小数
        const refundAmount = Math.round((finalAmount - serviceFee) * 100) / 100;

        return {
          success: true,
          canCancel: true,
          refundAmount: refundAmount,
          serviceFee: serviceFee,
          refundReason: '超过预计入场时间取消，扣除10%服务费',
          refundType: 'partial_refund'
        };
      }
    } catch (error) {
      console.error('计算取消退款失败:', error);
      return {
        success: false,
        error: error.message,
        canCancel: false
      };
    }
  }

  /**
   * 计算提前离场的退款金额
   * @param {Object} order - 订单信息
   * @param {Date} actualEndTime - 实际离场时间
   * @returns {Promise<Object>} 退款计算结果
   */
  async calculateEarlyDepartureRefund(order, actualEndTime) {
    try {
      const plannedStartTime = new Date(order.planned_start_time);
      const plannedEndTime = new Date(order.planned_end_time);
      const actualStartTime = new Date(order.actual_start_time || order.planned_start_time);
      
      // 计算原计划停车天数
      const plannedDays = pricingEngine.calculateParkingDays(plannedStartTime, plannedEndTime);
      
      // 计算实际停车天数
      const actualDays = pricingEngine.calculateParkingDays(actualStartTime, actualEndTime);
      
      if (actualDays >= plannedDays) {
        // 实际停车时间不少于计划时间，无需退款
        return {
          success: true,
          refundAmount: 0,
          refundReason: '实际停车时间不少于计划时间',
          refundType: 'no_refund',
          plannedDays,
          actualDays
        };
      }

      // 重新计算实际停车费用
      const actualPriceResult = await pricingEngine.calculatePrice(
        order.parking_lot_id, 
        actualStartTime, 
        actualEndTime
      );

      if (!actualPriceResult.success) {
        throw new Error('计算实际停车费用失败');
      }

      const actualAmount = actualPriceResult.total_amount;
      const originalAmount = parseFloat(order.total_amount);
      const discountAmount = parseFloat(order.discount_amount);
      
      // 计算应退金额（原总金额 - 实际停车费用）
      const refundBeforeDiscount = Math.max(0, originalAmount - actualAmount);
      
      // 如果有优惠券，按比例退还优惠金额
      let refundDiscountAmount = 0;
      if (discountAmount > 0 && originalAmount > 0) {
        refundDiscountAmount = Math.round((refundBeforeDiscount / originalAmount) * discountAmount * 100) / 100;
      }

      const totalRefundAmount = Math.round((refundBeforeDiscount - refundDiscountAmount) * 100) / 100;

      return {
        success: true,
        refundAmount: Math.max(0, totalRefundAmount),
        refundDiscountAmount,
        refundReason: `提前离场退款，实际停车${actualDays}天，计划${plannedDays}天`,
        refundType: 'early_departure_refund',
        plannedDays,
        actualDays,
        originalAmount,
        actualAmount,
        calculation: {
          planned_amount: originalAmount,
          actual_amount: actualAmount,
          refund_before_discount: refundBeforeDiscount,
          refund_discount: refundDiscountAmount,
          final_refund: totalRefundAmount
        }
      };

    } catch (error) {
      console.error('计算提前离场退款失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 计算延迟离场的补款金额
   * @param {Object} order - 订单信息
   * @param {Date} actualEndTime - 实际离场时间
   * @returns {Promise<Object>} 补款计算结果
   */
  async calculateLateDeparturePayment(order, actualEndTime) {
    try {
      const plannedStartTime = new Date(order.planned_start_time);
      const plannedEndTime = new Date(order.planned_end_time);
      const actualStartTime = new Date(order.actual_start_time || order.planned_start_time);
      
      // 计算原计划停车天数
      const plannedDays = pricingEngine.calculateParkingDays(plannedStartTime, plannedEndTime);
      
      // 计算实际停车天数
      const actualDays = pricingEngine.calculateParkingDays(actualStartTime, actualEndTime);
      
      if (actualDays <= plannedDays) {
        // 实际停车时间不超过计划时间，无需补款
        return {
          success: true,
          additionalAmount: 0,
          paymentReason: '实际停车时间未超过计划时间',
          paymentType: 'no_additional_payment',
          plannedDays,
          actualDays
        };
      }

      // 重新计算实际停车费用
      const actualPriceResult = await pricingEngine.calculatePrice(
        order.parking_lot_id, 
        actualStartTime, 
        actualEndTime
      );

      if (!actualPriceResult.success) {
        throw new Error('计算实际停车费用失败');
      }

      const actualAmount = actualPriceResult.total_amount;
      const originalAmount = parseFloat(order.total_amount);
      
      // 计算需要补交的金额
      const additionalAmount = Math.max(0, Math.round((actualAmount - originalAmount) * 100) / 100);

      return {
        success: true,
        additionalAmount,
        paymentReason: `延迟离场补款，实际停车${actualDays}天，计划${plannedDays}天`,
        paymentType: 'late_departure_payment',
        plannedDays,
        actualDays,
        originalAmount,
        actualAmount,
        calculation: {
          planned_amount: originalAmount,
          actual_amount: actualAmount,
          additional_payment: additionalAmount
        }
      };

    } catch (error) {
      console.error('计算延迟离场补款失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 生成退款单号
   * @param {string} orderNumber - 原订单号
   * @param {string} type - 退款类型
   * @returns {string} 退款单号
   */
  generateRefundNumber(orderNumber, type = 'RF') {
    const timestamp = Date.now();
    const random = Math.random().toString(36).substr(2, 4).toUpperCase();
    return `${type}${orderNumber.replace('PK', '')}${timestamp}${random}`;
  }
}

module.exports = new RefundCalculator();
